// +----------------------------------------------------------------------
// | JavaWeb_EleVue_Pro前后端分离旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2021 上海JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <javaweb520@gmail.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package com.javaweb.admin.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.XmlUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biz.smpaa.webservice.YsIntfce;
import com.javaweb.admin.entity.*;
import com.javaweb.admin.mapper.DPostResultXmlMapper;
import com.javaweb.admin.mapper.YYq005DetailMapper;
import com.javaweb.admin.mapper.YYq005Mapper;
import com.javaweb.admin.query.YYq005Query;
import com.javaweb.admin.service.Const;
import com.javaweb.admin.service.IYYq005Service;
import com.javaweb.admin.service.SQLDBQuery;
import com.javaweb.admin.vo.yyq005.YYq005InfoVo;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.common.utils.CommonUtils;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.JsonResult;
import com.javaweb.common.utils.StringUtils;
import com.javaweb.system.utils.ShiroUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import java.io.InputStream;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
  * <p>
  * 订单代填主表 服务类实现
  * </p>
  *
  * @author 鲲鹏
  * @since 2023-12-31
  */
@Service
public class YYq005ServiceImpl extends BaseServiceImpl<YYq005Mapper, YYq005> implements IYYq005Service {

    @Autowired
    private YYq005Mapper yYq005Mapper;

    @Autowired
    private YYq005DetailMapper yYq005DetailMapper;

    @Autowired
    private DPostResultXmlMapper postResultXmlMapper;

    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    public JsonResult getList(BaseQuery query) {
        YYq005Query yYq005Query = (YYq005Query) query;
        // 查询条件
        QueryWrapper<YYq005> queryWrapper = new QueryWrapper<>();
        // queryWrapper.orderByDesc("id");
        queryWrapper.select("replaceno,orderdate,status,empleeid,salesman,customername,shaddress,bzsm,ddlx,ddbh,psdbm,zwdhrq,sfbtdd,czlx,sjcgrq,dcpsbs,yyjhdh,jls,splx,yybm,supplierId");

        // 获取数据列表
        IPage<YYq005> page = new Page<>(yYq005Query.getPage(), yYq005Query.getLimit());
        IPage<YYq005> pageData = yYq005Mapper.selectPage(page, queryWrapper);
//        pageData.convert(x -> {
//            YYq005ListVo yYq005ListVo = Convert.convert(YYq005ListVo.class, x);
//            return yYq005ListVo;
//        });
        return JsonResult.success(pageData);
    }

    @Override
    public List<NCCustInfoDoc> getCustomerList(String custcode,String custname) {
        return yYq005Mapper.getCustomerList(custcode,custname);
    }

    @Override
    public List<NCCustAddrDoc> getCustomerAddressList(String custcode) {
        return yYq005Mapper.getCustomerAddressList(custcode);
    }

    @Override
    public List<YYq005Detail> getInvCustList(String yybm,String invcode, String invname) {
        return yYq005Mapper.getCustInvList(yybm,invcode,invname);
    }

    @Override
    public List<YYq005Detail> getInvAllList(String invcode, String invname) {
        return null;
    }

    @Override
    public List<YYq005Detail> getDetailList(String replaceno) {
        return yYq005Mapper.getDetailList(replaceno);
    }

    @Override
    public JsonResult create(YYq005Dto dto) {
        try {
            YYq005 entity = dto.getYq005();
            YYq005Detail[] yq005Details = dto.getYq005Details();
            String replaceno = "RP"+ DatePattern.PURE_DATETIME_FORMAT.format(DateUtils.now());
            QueryWrapper<YYq005> queryWrapper = new QueryWrapper<YYq005>().eq("replaceno",replaceno);
            queryWrapper.select("yybm,psdbm,ddlx,splx,ddbh,dcpsbs");
            YYq005 yq005 = yYq005Mapper.selectOne(queryWrapper);

            if(!StringUtils.isNull(yq005) && yq005.getStatus()!=0)
            {
                return JsonResult.error("该订单状态非【未提交】，不能再次保存。");
            }

            entity.setReplaceno(replaceno);
            entity.setStatus(0);
            entity.setSplx("1");
            entity.setDcpsbs("0");
            entity.setCzlx("1");
            entity.setEmpleeid(ShiroUtils.getUserAccount());
            entity.setJls(yq005Details.length);
            yYq005Mapper.insert(entity);
            Integer index = 0;
            for (YYq005Detail detail : yq005Details) {
                index++;
                detail.setSxh(index);
                //detail.setDcpsbs(1);
                detail.setCglx("1");
                detail.setCgjldw("1");
                detail.setYqbm(Const.YGPT_JGDM);
                detail.setReplaceno(entity.getReplaceno());
                yYq005DetailMapper.insert(detail);
            }
            return JsonResult.success(replaceno);
        }
        catch (Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }

    }


    private void appendItem(Document document, Element src,String elementName)
    {
        NodeList itemList = src.getChildNodes();
        Element elementItem =  document.createElement(elementName);
        for (int i = 0; i < itemList.getLength(); i++) {
            if(XmlUtil.isElement(itemList.item(i))) {
                Element ele = document.createElement(itemList.item(i).getNodeName());
                Text txtNode = document.createTextNode(itemList.item(i).getTextContent());
                ele.appendChild(txtNode);
                elementItem.appendChild(ele);
            }
        }
        Element elementG=XmlUtil.getRootElement(document);
        Element elementDetail =XmlUtil.getElement(elementG,"DETAIL");
        elementDetail.appendChild(elementItem);

    }
    @Override
    public JsonResult DDDTToYGPT(YYq005Dto dto) {
        ClassPathResource classPathResource = new ClassPathResource("nc/" + "YQ005.xml");
        InputStream inputStream039 = classPathResource.getStream();
        Document document003= XmlUtil.readXML(inputStream039);
        Element elementG=XmlUtil.getRootElement(document003);
        Element YsPsdHead = XmlUtil.getElement(elementG,"HEAD");
        Element YsPsdMain = XmlUtil.getElement(elementG,"MAIN");
        Element elementD = XmlUtil.getElement(elementG,"DETAIL");
        Element YsPsdDetail = XmlUtil.getElement(elementD,"STRUCT");
        String orderno = dto.getYq005().getReplaceno();
        QueryWrapper<YYq005> queryWrapper = new QueryWrapper<YYq005>().eq("replaceno",orderno);
        queryWrapper.select("yybm,psdbm,ddlx,splx,ddbh,dcpsbs,bzsm");
        YYq005 entity = yYq005Mapper.selectOne(queryWrapper);

        if(StringUtils.isNull(entity))
        {
            return JsonResult.error("无效的代填订单编号:"+orderno);
        }
        //判断订单编号是否已经更新
        if(!StringUtils.isEmpty(entity.getDdbh()))
        {
            return JsonResult.error("代填订单已成功上传，不能重复提交。阳光平台返回订单编号【"+entity.getDdbh()+"】");
        }
        HashMap<String,Object> param = new HashMap<>();
        param.put("replaceno",orderno);
        List<YYq005Detail> detailList = yYq005DetailMapper.selectByMap(param);
        String czlx = "1"; //新增
        String mac = "";
        String ip = NetUtil.getLocalhostStr();
        StringBuilder sb = new StringBuilder();
        String[] result = null;
        Document docSubmit003 = null;

        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        CommonUtils.XmlSetNodeContent(YsPsdHead,"IP",ip);
        CommonUtils.XmlSetNodeContent(YsPsdHead,"MAC",mac.replaceAll(":","").replaceAll("-",""));
        CommonUtils.XmlSetNodeContent(YsPsdHead,"BZXX","");

        CommonUtils.XmlSetNodeContent(YsPsdMain,"CZLX",czlx);
        CommonUtils.XmlSetNodeContent(YsPsdMain,"YYBM",entity.getYybm());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDBM",entity.getPsdbm());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"DDLX",entity.getDdlx());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"DDBH","");
        CommonUtils.XmlSetNodeContent(YsPsdMain,"YYJHDH","");
        CommonUtils.XmlSetNodeContent(YsPsdMain,"ZWDHRQ","");
        CommonUtils.XmlSetNodeContent(YsPsdMain,"JLS",String.valueOf(detailList.size()));
        for (int i = 0; i < detailList.size(); i++) {
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"SXH",String.valueOf(detailList.get(i).getSxh()));
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"CGLX","1");
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"SPLX",entity.getSplx());
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"ZXSPBM",detailList.get(i).getZxspbm());
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"CGJLDW",detailList.get(i).getCgjldw());
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"CGSL",String.valueOf(detailList.get(i).getCgsl()));
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"CGDJ",String.valueOf(detailList.get(i).getCgdj()));
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"YQBM",detailList.get(i).getYqbm());
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"DCPSBS",entity.getDcpsbs());
            CommonUtils.XmlSetNodeContent(YsPsdDetail,"BZSM",entity.getBzsm());
            if(i==0) {
                docSubmit003 = XmlUtil.readXML(XmlUtil.toStr(document003));
            } else {
                appendItem(docSubmit003,YsPsdDetail,"STRUCT");
            }

        }
        try {
            result = YsDDDTUpload(XmlUtil.toStr(docSubmit003, true), orderno);
            if ("00000".equals(result[4])) {
                return JsonResult.success();
            } else {
                return JsonResult.error(result[4]+result[5]+":"+result[6]);
            }
        }
        catch (Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    public JsonResult getLogList(String postid) {
        List<PostResultXml> postResultXmls = postResultXmlMapper.getLogList(postid);
        return JsonResult.success(postResultXmls);
    }

    @Override
    public JsonResult DDDTConfirm(YYq005Dto dto) {
        ClassPathResource classPathResource = new ClassPathResource("nc/" + "YQ006.xml");
        InputStream inputStream039 = classPathResource.getStream();
        Document document003= XmlUtil.readXML(inputStream039);
        Element elementG=XmlUtil.getRootElement(document003);
        Element YsPsdHead = XmlUtil.getElement(elementG,"HEAD");
        Element YsPsdMain = XmlUtil.getElement(elementG,"MAIN");
        String orderno = dto.getYq005().getReplaceno();
        QueryWrapper<YYq005> queryWrapper = new QueryWrapper<YYq005>().eq("replaceno",orderno);
        queryWrapper.select("yybm,psdbm,ddlx,splx,ddbh,dcpsbs");
        YYq005 entity = yYq005Mapper.selectOne(queryWrapper);

        if(StringUtils.isNull(entity))
        {
            return JsonResult.error("无效的代填订单编号:"+orderno);
        }
        //判断订单编号是否已经更新
        if(StringUtils.isEmpty(entity.getDdbh()))
        {
            return JsonResult.error("代填订单尚未上传阳光平台，不能确认。");
        }
        HashMap<String,Object> param = new HashMap<>();
        param.put("replaceno",orderno);
        List<YYq005Detail> detailList = yYq005DetailMapper.selectByMap(param);
        String czlx = "1"; //新增
        String mac = "";
        String ip = NetUtil.getLocalhostStr();
        StringBuilder sb = new StringBuilder();
        String[] result = null;
        Document docSubmit003 = null;

        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        CommonUtils.XmlSetNodeContent(YsPsdHead,"IP",ip);
        CommonUtils.XmlSetNodeContent(YsPsdHead,"MAC",mac.replaceAll(":","").replaceAll("-",""));
        CommonUtils.XmlSetNodeContent(YsPsdHead,"BZXX","");

        CommonUtils.XmlSetNodeContent(YsPsdMain,"YYBM",entity.getYybm());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDBM",entity.getPsdbm());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"DDLX",entity.getDdlx());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"DDBH",entity.getDdbh());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"SPSL",String.valueOf(detailList.size()));
        docSubmit003 = XmlUtil.readXML(XmlUtil.toStr(document003));
        try {
            result = YsDDDTConfirm(XmlUtil.toStr(docSubmit003, true), orderno);
            if ("00000".equals(result[4])) {
                return JsonResult.success();
            } else {
                return JsonResult.error(result[4]+result[5]+":"+result[6]);
            }
        }
        catch (Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }    }

    public String[] YsDDDTUpload(String YsXml, String orderno) throws SQLException {
        //阳光配送单传报
        String[] rtnPsd = YsIntfce.SendYgRecv2019("YQ005", YsXml);
        String ddmxbh = "";
        if ("00000".equals(rtnPsd[4]) || ("20000".equals(rtnPsd[4]) && rtnPsd[6].contains("已响应")))
        {
            //for (int i = 0; i < ddmxbhs.length; i++) {
                //更新订单响应类型
                String ddbh = "";
                //从返回结果xml报文中获取订单编号
            Document result = XmlUtil.readXML(rtnPsd[2]);
            Element elementG=XmlUtil.getRootElement(result);
            Element YsMain = XmlUtil.getElement(elementG,"MAIN");
            ddbh = CommonUtils.XmlGetNodeContent(YsMain,"DDBH");

            SQLDBQuery.updateYQ005YgddDdbh(orderno, ddbh);
                //写入阳光配送单的日志
                SQLDBQuery.insertOrderTrackDetail(ddbh, Const.ORDER_03, DateUtil.now() +" "+ Const.ORDER_05_01 + "," + "成功！");
            //}
        }

        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnPsd, orderno, Const.YQ005_TXT);
        return rtnPsd;
    }

    public String[] YsDDDTConfirm(String YsXml, String orderno) throws SQLException {
        //阳光配送单传报
        String[] rtnPsd = YsIntfce.SendYgRecv2019("YQ006", YsXml);
        String ddmxbh = "";
        if ("00000".equals(rtnPsd[4]) || ("20000".equals(rtnPsd[4]) && rtnPsd[6].contains("已响应")))
        {
            //for (int i = 0; i < ddmxbhs.length; i++) {
            //确认成功，更新状态为已确认
            SQLDBQuery.updateYQ005Status(orderno,2);
            //写入阳光配送单的日志
            SQLDBQuery.insertOrderTrackDetail(orderno, Const.ORDER_03, DateUtil.now() +" "+ Const.ORDER_05_02 + "," + "成功！");
            //}
        }
        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnPsd, orderno, Const.YQ006_TXT);
        return rtnPsd;
    }

    /**
     * 获取详情Vo
     *
     * @param id 记录ID
     * @return
     */
    @Override
    public Object getInfo(Serializable id) {
        YYq005 entity = (YYq005) super.getInfo(id);
        // 返回视图Vo
        YYq005InfoVo yYq005InfoVo = new YYq005InfoVo();
        // 拷贝属性
        BeanUtils.copyProperties(entity, yYq005InfoVo);
        return yYq005InfoVo;
    }

    /**
     * 添加、更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult edit(YYq005 entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
        } else {
        }
        return super.edit(entity);
    }

    /**
     * 删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult delete(YYq005 entity) {
        entity.setMark(0);
        return super.delete(entity);
    }

    @Override
    public JsonResult deleteByIds(String[] ids) {
        try {
            for (String id : ids) {
                Map<String, Object> param = new HashMap<>();
                param.put("replaceno", id);
                yYq005DetailMapper.deleteByMap(param);
                yYq005Mapper.deleteByMap(param);
            }
            return JsonResult.success();
        } catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }

    }
}